<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="父节点" prop="parentId">
        <el-cascader v-model="parentIdArr" :props="props" clearable></el-cascader>
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入名称" clearable
          size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="深度" prop="depth">
        <el-select v-model="queryParams.depth" placeholder="请输入深度" clearable size="small">
          <el-option label="0级" value="0" />
          <el-option label="1级" value="1" />
          <el-option label="2级" value="2" />
          <el-option label="3级" value="3" />
          <el-option label="4级" value="4" />
          <el-option label="5级" value="5" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="状态" clearable size="small">
          <el-option v-for="(val, key) in statusOptions" :value="key" :label="val" :key="key"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" 
          @click="handleAdd" v-hasPermi="['system:area:add']" >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" icon="el-icon-edit" size="mini" :disabled="single" 
          @click="handleUpdate" v-hasPermi="['system:area:edit']" >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple"
          @click="handleDelete" v-hasPermi="['system:area:remove']" >删除</el-button>
      </el-col>
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="areaList" @selection-change="handleSelectionChange"
      @sort-change="handleSortChange">
      <el-table-column type="selection" fixed width="55" align="center" />
      <el-table-column label="名称" align="left" prop="name" :show-overflow-tooltip="true" min-width="80"/>
      <el-table-column label="父节点" align="left" prop="parentArea.name" :show-overflow-tooltip="true" min-width="80"/>
      <el-table-column label="简拼" align="left" prop="abridge" />
      <el-table-column label="电话号段" align="left" prop="phoneCode" />
      <el-table-column label="邮编" align="left" prop="postCode" />
      <el-table-column label="经度" align="left" prop="lng" :show-overflow-tooltip="true" min-width="100"/>
      <el-table-column label="纬度" align="left" prop="lat" :show-overflow-tooltip="true" min-width="100"/>
      <el-table-column label="排序" align="left" prop="sequence" />
      <el-table-column sortable label="深度" align="center" prop="depth" />
      <el-table-column sortable label="节点个数" align="left" prop="childsLength" min-width="100"/>
      <el-table-column label="路径名称" align="left" prop="pathName" :show-overflow-tooltip="true" min-width="180"/>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag type="info" size="small" v-if="scope.row.status!==null">{{statusOptions[scope.row.status]}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width" min-width="180">
        <template slot-scope="scope" v-if="scope.row.depth !==0 ">
          <el-button size="mini" type="text" icon="el-icon-edit"
            @click="handleUpdate(scope.row)" v-hasPermi="['system:area:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-view"
            @click="handleDetail(scope.row)" v-hasPermi="['system:area:query']">详情</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete"
            @click="handleDelete(scope.row)" v-hasPermi="['system:area:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改区域对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="650px" append-to-body :close-on-click-modal="false" 
       @close="closeDialog">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" :disabled="showDetail">
        <el-row>
          <el-col :span="12">
            <el-form-item label="区域名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="父节点" prop="parentId">
              <el-cascader ref="cascaderArea" placeholder="请选择父节点" v-model="form.parentIdArr" :props="propsEdit" 
                :options="cascaderData"></el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="电话号段" prop="phoneCode">
              <el-input v-model="form.phoneCode" placeholder="请输入电话号段" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="区域邮编" prop="postCode">
              <el-input v-model="form.postCode" placeholder="请输入邮编" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="区域经度" prop="lng">
              <el-input v-model="form.lng" placeholder="请输入经度" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="区域纬度" prop="lat">
              <el-input v-model="form.lat" placeholder="请输入纬度" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="区域排序" prop="sequence">
              <el-input-number placeholder="请输入排序" v-model="form.sequence" controls-position="right" :min="1" :max="99"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="区域状态">
              <el-radio-group v-model="form.status">
                <el-radio v-for="(val, key) in statusOptions" :label="key" :key="key">
                  {{val}}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="!showDetail">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listArea, getArea, delArea, addArea, updateArea, exportArea, getAreaListCascader } from "@/api/system/area";
let parentId = 1;// 起始父节点id
let parentIdEdit = 1;// 起始父节点id
let depthMax = 2;// 对多获取三级级联
let haveIdArr = [];// 修改是，，已经返回的节点数组
export default {
  name: "Area",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 区域表格数据
      areaList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        parentId: null,
        abridge: null,
        pinyin: null,
        phoneCode: null,
        postCode: null,
        path: null,
        note: null,
        mark: null,
        lng: null,
        lat: null,
        sequence: null,
        depth: null,
        childsLength: null,
        pathName: null,
        geohash: null,
        status: null,
        isDelete: null,
        depthMax: 3,
        argumentsOrder:'depth:asc;sequence:asc;',
      },
      parentIdArr: null,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      // ++++++++++++++++++++++++++++++
      showDetail: false,
      cascaderData: [],
      statusOptions: null,
      props: {
        checkStrictly: true,
        lazy: true,
        lazyLoad (node, resolve) {
          if (node.value) {
            parentId = node.value;
          }
          let cascaderParam = {};
          cascaderParam.parentId = parentId;
          cascaderParam.depthMax = depthMax;
          getAreaListCascader(cascaderParam).then(response => {
            resolve(response.data);
          });
        }
      },
      propsEdit: {
        checkStrictly: true,
        lazy: true,
        lazyLoad (node, resolve) {
          if (node.value) {
            parentIdEdit = node.value;
          }
          var index = haveIdArr.findIndex(item => item=== node.value)
          console.info(haveIdArr)
          console.info(node.value)
          if (index>=0) {
            resolve(null);
            return;
          }
          let cascaderParam = {};
          cascaderParam.parentId = parentIdEdit;
          cascaderParam.depthMax = depthMax;
          getAreaListCascader(cascaderParam).then(response => {
            resolve(response.data);
          });
        }
      },
      
    };
  },
  created() {
    this.getList();
    this.getEnumMap("StatusEnum").then(response => {// 状态
      this.statusOptions = response.data;
    });
  },
  methods: {
    handleSortChange(val) {
      if(val.column) {
        if (val.order ===null) {
          this.queryParams.argumentsOrder = 'depth:asc;sequence:asc;';
        } else {
          let orderStr = val.order ==='ascending'?'asc':'desc';
          this.queryParams.argumentsOrder = this.toLine(val.prop)+":"+orderStr+";";
        }
        //调用排序接口
        this.getList();
      }      
    },
    // 关闭时设置默认活动tab
    closeDialog() {
      this.showDetail = false;
      this.cascaderData = [];
    },
    /** 查询区域列表 */
    getList() {
      this.loading = true;
      if (this.parentIdArr && this.parentIdArr.length>0) {
        this.queryParams.parentId = this.parentIdArr[this.parentIdArr.length-1]
      } else {
        this.queryParams.parentId = null;
      }
      
      listArea(this.queryParams).then(response => {
        this.areaList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.cascaderData = [];
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        parentId: null,
        abridge: null,
        pinyin: null,
        phoneCode: null,
        postCode: null,
        path: null,
        note: null,
        mark: null,
        lng: null,
        lat: null,
        sequence: 99,
        depth: null,
        childsLength: null,
        pathName: null,
        geohash: null,
        status: '1',
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        isDelete: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加区域";

  
      let cascaderParam = {};
      cascaderParam.parentId = 1;
      cascaderParam.depthMax = 2;
      getAreaListCascader(cascaderParam).then(response => {
        this.cascaderData = response.data
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getArea(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改区域";

        this.form.status = String(this.form.status);
        console.info(this.form.status)
        this.cascaderData = response.cascaderData;
        this.form.parentIdArr;
        haveIdArr = JSON.parse(JSON.stringify(this.form.parentIdArr)) 
        haveIdArr.pop();
        this.form.parentIdArr.pop();
      });
    },
    /** 查看按钮操作 */
    handleDetail(row) {
      this.reset();
      const id = row.id || this.ids
      getArea(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "查看区域";
        this.showDetail = true;

        
        this.form.status = String(this.form.status);
        console.info(this.form.status)
        this.cascaderData = response.cascaderData;
        this.form.parentIdArr;
        haveIdArr = JSON.parse(JSON.stringify(this.form.parentIdArr)) 
        haveIdArr.pop();
        this.form.parentIdArr.pop();
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          console.info(this.form.parentIdArr)
          if (this.form.parentIdArr!==null && this.form.parentIdArr !== undefined && this.form.parentIdArr.length != 0) {       
            let arr = this.$refs['cascaderArea'].getCheckedNodes()[0].pathLabels
            this.form.pathNameArr = arr;
          }

          if (this.form.id != null) {
            updateArea(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addArea(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除区域编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delArea(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有区域数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportArea(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    }
  }
};
</script>
